#coding:utf8
"""
多进程处理
"""
import os,time
import re
import pandas as pd
from utils.get_features import get_feature_data_02
from multiprocessing import Process, Pool


def run_a_sub_proc(code, df_total, latest5date):
    try:
        if re.findall(r"^4|^3|^8|^688", code):
            return None

        print(f"extract data of: {code}")
        df_tmp = pd.DataFrame(data=None, columns=None)
        dfs = []
        for day in latest5date:
            t2 = df_total[(df_total['股票代码'] == code) & (df_total['日期'] == day)]
            t21 = df_total.loc[df_total['股票代码'] == code]
            t22 = df_total.loc[df_total['日期'] == day]
            if t2.empty or t2['股票代码'].isnull().any() or t2['股票名称'].isnull().any():
                break
            dfs.append(t2)
        df_tmp = pd.concat(dfs, ignore_index=True)
        df_tmp = df_tmp.reset_index(drop=True)

        # print(df_tmp)
        if df_tmp.empty or len(df_tmp) < 5:
            return None
        else:
            features = get_feature_data_02(df_tmp, infer=True)
            if not features:
                return None
            elif features[1]:
                return features[1]

    except Exception as e:
        print(f"error: {code}")
        return None


def run_multi_task_by_process(stock_list, df_total, latest5date):
    print(f'主进程（{os.getpid()}）开始...')

    p = Pool(3)
    result = []
    for i in range(len(stock_list)):
        result.append(p.apply_async(run_a_sub_proc, args=(stock_list[i],df_total,latest5date)))
    p.close()
    p.join()

    features = []
    for i in result:
        t1 = i.get()
        if t1:
            #print(i.get())
            features.append(t1)

    return features


if __name__ == '__main__':
    print()

